<?php

namespace paper\http;

class RoutingRules
{
    public array $routes = [];
    public int $pos = -1;

    /**
     * @return array
     */
    public function getRoutes(): array
    {
        return $this->routes;
    }

    function any($pattern, $to): static
    {
        $this->routeRegister(null, $pattern, $to);
        return $this;
    }

    function get($pattern, $to): static
    {
        $this->routeRegister(null, $pattern, $to);
        return $this;
    }

    function group($prefix, \Closure $closure): static
    {
        $this->routeRegister($prefix, $closure, null);
        return $this;
    }



    private function routeRegister(?string $prefix, $pattern, $to)
    {
        $this->nextRoute();
        $route = &$this->current();
        if (is_string($pattern)) {
            if (!str_ends_with($pattern, '/'))
                $pattern .= '/';
        }
        $route['pattern'] = $pattern;
        $route['to'] = $to;
        $route['prefix'] = $prefix;
        $route['namespace'] = '';
        $route['middlewares'] = [];
        $route['match'] = [];
        $route['withoutMiddlewares'] = [];
//        $route['finish'] = false;
    }


    function namespace(string $namespace): static
    {
        $route = &$this->current();
        $route['namespace'] = $namespace;
        return $this;
    }

    function middlewares(array $middleware): static
    {
        $route = &$this->current();
        $route['middlewares'] = $middleware;
        return $this;
    }

    function withoutMiddlewares(array $middleware): static
    {
        $route = &$this->current();
        $route['withoutMiddlewares'] = $middleware;
        return $this;
    }

    function nextRoute()
    {
        $this->pos++;
        $this->routes[$this->pos] = [];
    }

    function &current()
    {
        return $this->routes[$this->pos];
    }
}